package com.dbexposer.db.mybatis.generator;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.TopLevelClass;

public class GeneratorInterceptorPlugin extends PluginAdapter {

	private static Map<String, GeneratorInfo> infosByTable;
	
	public static Map<String, GeneratorInfo> getInfosByTable() {
		return infosByTable;
	}

	public GeneratorInterceptorPlugin() {
		infosByTable = new LinkedHashMap<String, GeneratorInfo>();
	}
	
	@Override
	public void initialized(IntrospectedTable introspectedTable) {
		String fqnTableName = introspectedTable.getFullyQualifiedTableNameAtRuntime();
		GeneratorInfo info = new GeneratorInfo(introspectedTable);
		infosByTable.put(fqnTableName, info);
	}
	
	private GeneratorInfo getInfo(IntrospectedTable table) {
		String fqnTableName = table.getFullyQualifiedTableNameAtRuntime();
		return infosByTable.get(fqnTableName);
	}
	
	// XXX does this plugin really need config validation?
	public boolean validate(List<String> arg0) {
		return true;
	}

	// Mappers
	@Override
	public boolean clientGenerated(Interface interfaze, TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		// TODO Auto-generated method stub
		getInfo(introspectedTable).modelDAO = interfaze;
		return true;
	}

	// Bean entities
	@Override
	public boolean modelBaseRecordClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		getInfo(introspectedTable).modelBean = topLevelClass;
		return true;
	}

	// Example criteria
	@Override
	public boolean modelExampleClassGenerated(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
		getInfo(introspectedTable).modelExample = topLevelClass;
		return true;
	}
	
	public static class GeneratorInfo {

		private IntrospectedTable modelTable;
		private TopLevelClass modelBean;
		private TopLevelClass modelExample;
		private Interface modelDAO;

		public GeneratorInfo(IntrospectedTable introspectedTable) {
			// TODO Auto-generated constructor stub
		}

		public IntrospectedTable getModelTable() {
			return modelTable;
		}

		public TopLevelClass getModelBean() {
			return modelBean;
		}

		public TopLevelClass getModelExample() {
			return modelExample;
		}

		public Interface getModelDAO() {
			return modelDAO;
		}

	}
	
}
